package com.lagou.unpack;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * @description: 客户端
 * @author: yx
 * @date: 2021/11/10 9:31
 */
public class NettyClientDemo {

    public static void main(String[] args) throws InterruptedException {
        //1. 创建一个线程组
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        //2. 创建一个启动助手
        Bootstrap bootstrap = new Bootstrap();
        //3. 注册线程组
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)//4. 设置客户端通道实现为NIO
                .handler(new ChannelInitializer<SocketChannel>() {//5. 创建一个通道初始化对象
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {//6. 配置自定义拦截器
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new NettyClientHandler());
                    }
                });
        //7. 启动客户端, 等待连接服务端, 同时将异步改为同步
        ChannelFuture future = bootstrap.connect("127.0.0.1", 9999);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    System.out.println("服务端连接成功========");
                }else {
                    System.out.println("服务端连接失败========");
                }
            }
        });
        //8. 关闭通道(不是真正意义上的关闭,而是一直监听通道关闭状态),异步改同步
        future.channel().closeFuture().sync();
        //9. 关闭线程组
        eventLoopGroup.shutdownGracefully();
    }

}
